package dao

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/pkg/errors"
	"study-demo/internal/model"
)

/***
	获取商品属性
*/
func(d *dao) productFeature(c context.Context, productId int64) (model.ProductFeature, error) {
	querySql := fmt.Sprintf("SELECT * FROM `t_product_feature` WHERE product_id=?;")
	var productFeature model.ProductFeature
	featureerr := d.db.QueryRow(c, querySql, productId).Scan(&productFeature.ProductId, &productFeature.PColor, &productFeature.PHeight)
	if featureerr != nil {
		return productFeature, errors.Wrapf(featureerr, "get ProductFeature err#productId %d", productId)
	}

	return productFeature, nil
}

/***
	获取商品详情
*/
func (d *dao)GetProductDetail(c context.Context, productId int64) (model.Product, error){
	querySql := fmt.Sprintf("SELECT * FROM `t_product` WHERE product_id=?;")
	var product model.Product
	err := d.db.QueryRow(c, querySql, productId).Scan(&product.ProductId, &product.Name, &product.ProductCode)

	// 如果函数/方法不打算处理错误，或者无法处理（比如此错误由于外部输入有误导致查询失败，应该记录关键错误信息放入warp，往上抛。
	if err != nil {
		return product, errors.Wrapf(err, "get product err#productId %d", productId)
	}

	if product.ProductFeature, err = d.productFeature(c, productId); err != nil {
		if err == sql.ErrNoRows {
			//如果查询过程关联内容出异常，此部分错误可以函数内部降级处理，错误返回
			fmt.Printf("ProductFeature not found, %v\n", err)
			return product, nil
		}
		return product, errors.WithMessagef(err, "get product err#productId %d", productId)
	}

	return product, nil
}

